package com.zbdx.controller;

import com.google.gson.Gson;
import com.zbdx.domain.User;
import com.zbdx.service.UserService;
import com.zbdx.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet{
    private UserService userService = new UserServiceImpl();

    //一次完整的请求包括请求和响应
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
            /*String name = req.getParameter("name");
            System.out.println(name);
            resp.getWriter().write("测试");*/
        String method = req.getParameter("method");
        System.out.println("method = " + method);
        if("findAll".equals(method)){
            try {
                this.findAll(req,resp);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else if("findById".equals(method)){
            try {
                this.findById(req,resp);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else if("addUser".equals(method)){
            try {
                this.addUser(req,resp);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else if("modifyUser".equals(method)){
            try {
                this.modifyUser(req,resp);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else if("removeById".equals(method)){
            try {
                this.removeById(req,resp);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else if ("findBySearch".equals(method)) {
            try {
                this.findBySearch(req,resp);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else{
            System.out.println("请求地址错误");
        }
    }

    private void findBySearch(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {

        String name = req.getParameter("name");

        System.out.println("name = "+name);

        List<User> list = userService.findBysearch(name);
        //使用哈希表存储数据
        HashMap<String,Object> map = new LinkedHashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",100);
        map.put("data",list);
        System.out.println(map);
        //将map转换为JSON对象
        Gson gson = new Gson();
        String json = gson.toJson(map);
        System.out.println("json="+json);
        PrintWriter writer = resp.getWriter();
        writer.print(json);
        writer.close();
    }

    private void removeById(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        String idParam = req.getParameter("id");
        System.out.println("id = " + idParam);
        // 确保 id 参数不为空并转换为整数
        if (idParam != null) {
            int id = Integer.parseInt(idParam);
            // 调用服务层删除用户
            boolean flag = userService.deleteById(id);
            // 返回结果给前端
            PrintWriter writer = resp.getWriter();
            if (flag) {
                writer.print(1); // 删除成功
            } else {
                writer.print(0); // 删除失败
            }
            writer.close();
        } else {
            // 如果 id 参
            // 数为空，返回失败
            System.out.println("用户ID为空");
            resp.getWriter().print(0);
        }
        /*String[] ids = req.getParameterValues("ids[]"); // 接收 IDs
        if (ids != null) {
            List<Integer> idList = Arrays.stream(ids).map(Integer::parseInt).collect(Collectors.toList());
            boolean flag = userService.bathDeleteUser(idList); // 调用删除方法
            if(flag) resp.getWriter().print(1); // 返回影响的行数
            else resp.getWriter().print(0);
        } else {
            resp.getWriter().print(0);
        }*/
    }

    private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String data = req.getParameter("data");
        System.out.println("data = " + data);
        Gson gson = new Gson();
        User user = gson.fromJson(data,User.class);
        boolean flag = userService.update(user);
        PrintWriter writer = resp.getWriter();
        if(flag){
            writer.print(1);
        }else writer.print(0);
        writer.close();
    }

    private void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        String data = req.getParameter("data");
        System.out.println("data = " + data);
        Gson gson = new Gson();
        User user = gson.fromJson(data,User.class);
        boolean flag = userService.addUser(user);
        PrintWriter writer = resp.getWriter();
        if(flag){
            writer.print(1);
        }else writer.print(0);
        writer.close();
    }

    private void findById(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
        String id = req.getParameter("id");
        String flag = req.getParameter("flag");
        System.out.println(flag);
        int F = Integer.parseInt(flag);
        System.out.println(F);
        System.out.println("id = " + id);
        if(id != null){
            int uid = Integer.parseInt(id);
            User user = userService.selectById(uid);
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            if(F==1){
                req.getRequestDispatcher("page/user/UserDetail.jsp").forward(req,resp);
            }else{
                req.getRequestDispatcher("page/user/editUser.jsp").forward(req,resp);
            }
        }else{
            System.out.println("用户ID为空");
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        List<User> list = userService.findAll();
        int count = list.size();
        //使用HashMap
        HashMap<String,Object> map = new LinkedHashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",list);
        System.out.println(map);
        Gson gson = new Gson();
        String json = gson.toJson(map);
        System.out.println("json = " + json);
        PrintWriter writer = resp.getWriter();
        writer.print(json);
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

}
